package www.houdoudou.com.common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class ConnFactory {

	
	public static Connection currentConn=null;
	public static List<String> CurrentUser= new ArrayList<String>();
	public static Connection  getCurrentConnection(String user)  
        {  CurrentUser.add(user);
		try {
			if(currentConn==null){
			currentConn=getConnection();  
			  }	else{ 
				  if(!currentConn.isValid(4000)){			
			         currentConn.close(); 
			         currentConn= getConnection();}
			      }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
                return currentConn;       
         }
	
	public static Connection  getConnection()  
    {    Connection conn = null;
         String url1="com.microsoft.sqlserver.jdbc.SQLServerDriver";  
          String url2="jdbc:sqlserver://localhost:1433;DatabaseName=HoudouDB";  
       //  String url2="jdbc:microsoft:sqlserver://localhost:1433";  
         String username="sa";  
         String passwrd="NewPassword";  
         try  
         {  
             Class.forName(url1);  
             conn=DriverManager.getConnection(url2,username,passwrd); 
            
         }  
         catch(Exception ex)  
         {  
               ex.printStackTrace();
         }
         
         if(conn!=null) { System.out.println("创建 SQL Connection 成功-- conn is  :"+conn);}
         else { System.out.println("创建 SQL Connection 失败");}
      return conn;
        
    }
	
	 public static void closeConn(String user,PreparedStatement pstm,Statement stm, ResultSet rs){
		 
		 
			try {
				if(rs!=null) rs.close();
				 if(stm!=null) stm.close();
				 if(pstm!=null) pstm.close();
				 if(del_user(user)) {currentConn.close(); System.out.println("-------------在关闭数据库连接----------------------");}
				 
				
				 
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
              }
	
	private static boolean del_user(String user){
		boolean  isNoUser=false;
		for(int i=CurrentUser.size()-1;i>=0;i--){
			if(CurrentUser.get(i).equals(user)) {
				CurrentUser.remove(i);}
			if(CurrentUser.size()==0){
				isNoUser=true;
			}
		}
		return isNoUser;
		
	}
}
